<template>
  <div class="table-editor-container">
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>其他配置</span>
          <div class="header-buttons">
            <el-button type="info" size="small" @click="showAddTabDialog">新增页签</el-button>
            <el-button type="primary" size="small" @click="refreshData" :loading="isRefreshing">刷新</el-button>
            <el-button type="success" size="small" @click="saveData">保存</el-button>
          </div>
        </div>
      </template>
      <el-tabs v-model="activeTab" @tab-click="handleTabClick" type="card" closable @tab-remove="handleTabRemove">
        <el-tab-pane
          v-for="tab in tabConfigs"
          :key="tab.id"
          :label="tab.label"
          :name="tab.name"
          :closable="tab.isRemovable"
        >
          <template #label>
            <span @dblclick="startEditTabLabel(tab)" class="tab-label">
              <span v-if="editingTabId !== tab.id">{{ tab.label }}</span>
              <el-input
                v-else
                v-model="editingTabLabel"
                size="small"
                @blur="finishEditTabLabel"
                @keyup.enter="finishEditTabLabel"
                @keyup.esc="cancelEditTabLabel"
                ref="tabLabelInput"
                style="width: 100px;"
              />
            </span>
          </template>
          <div class="selected-cell-display">
            <span class="display-label">当前选中内容：</span>
            <span class="display-content">{{ selectedCellContent }}</span>
          </div>
          <div class="table-container">
            <hot-table
              :ref="(el: any) => setTableRef(el, tab.id)"
              :settings="getTableSettings(tab)"
            ></hot-table>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 新增页签对话框 -->
    <el-dialog v-model="addTabDialogVisible" title="新增页签" width="400px" :close-on-click-modal="false">
      <el-form ref="addTabFormRef" :model="addTabForm" :rules="addTabFormRules" label-width="80px">
        <el-form-item label="页签名称" prop="label">
          <el-input v-model="addTabForm.label" placeholder="请输入页签名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addTabDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAddTab" :loading="isSubmitting">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, watch, onUnmounted, onBeforeMount } from 'vue'
import { HotTable } from '@handsontable/vue3'
import Handsontable from 'handsontable'
import { registerAllModules } from 'handsontable/registry'
import { registerLanguageDictionary, zhCN } from 'handsontable/i18n'
import 'handsontable/dist/handsontable.full.min.css'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { TabsPaneContext } from 'element-plus'
import {
  esSaveConfig,
  esGetLatestConfig,
  type ConfigType,
  type ConfigData,
  type CellMeta,
  type TableData,
  type TableMeta,
  initializeESIndices,
  type TabConfig,
  esGetTabConfig,
  addNewTab,
  removeTab,
  updateTabLabel,
  clearTabConfigCache,
  getDefaultTabConfig,
  esSaveTabConfig
} from './ConfigService'
import type { FormInstance, FormRules } from 'element-plus'

// 注册所有Handsontable模块
registerAllModules()
// 注册中文语言包
registerLanguageDictionary(zhCN)

// 当前激活的页签
const activeTab = ref('talent')

// 页签配置
const tabConfigs = ref<TabConfig[]>([])

// 表格数据 - 改为 Map 存储多个页签的数据
const tableDataMap = ref<Map<string, TableData>>(new Map())

interface HotTableMethods {
  hotInstance: Handsontable
}

// 组件引用 - 改为 Map 存储多个表格实例
const tableComponentsMap = ref<Map<string, HotTableMethods>>(new Map())

// 存储所有表格组件的 ref
const tableRefs = ref<Record<string, HotTableMethods>>({})

// 表格高度
const tableHeight = ref(500)

// 计算表格高度
const calculateTableHeight = () => {
  // 计算总的偏移量
  const totalOffset = 280

  // 设置表格高度
  const height = window.innerHeight - totalOffset
  tableHeight.value = height

  // 更新所有表格的高度
  tabConfigs.value.forEach(tab => {
    const tableComponent = tableRefs.value[tab.id] || tableComponentsMap.value.get(tab.id)
    if (tableComponent?.hotInstance) {
      tableComponent.hotInstance.updateSettings({ height }, false)
    }
  })
}

// 存储单元格元数据 - 改为 Map 存储多个页签的元数据
const metadataMap = ref<Map<string, TableMeta>>(new Map())

// 新增页签相关状态
const addTabDialogVisible = ref(false)
const addTabFormRef = ref<FormInstance>()
const addTabForm = ref({
  label: ''
})
const addTabFormRules: FormRules = {
  label: [
    { required: true, message: '请输入页签名称', trigger: 'blur' },
    { min: 1, max: 20, message: '页签名称长度在 1 到 20 个字符', trigger: 'blur' }
  ]
}
const isSubmitting = ref(false)

// 编辑页签标签相关状态
const editingTabId = ref<string | null>(null)
const editingTabLabel = ref('')
const tabLabelInput = ref<HTMLInputElement | null>(null)

// 获取当前页签的元数据
const getCurrentMetadata = (): TableMeta => {
  const currentTab = tabConfigs.value.find(t => t.name === activeTab.value)
  if (!currentTab) return { cells: {}, columnWidths: {} }

  if (!metadataMap.value.has(currentTab.id)) {
    metadataMap.value.set(currentTab.id, { cells: {}, columnWidths: {} })
  }
  return metadataMap.value.get(currentTab.id)!
}

// 自定义单元格渲染器
const customRenderer = (instance: Handsontable, td: HTMLTableCellElement, row: number, col: number, prop: string | number, value: any, cellProperties: any) => {
  // 调用默认渲染器
  Handsontable.renderers.TextRenderer(instance, td, row, col, prop, value, cellProperties);

  // 应用自定义背景色
  const key = `${row}-${col}`;
  const metadata = getCurrentMetadata();
  if (metadata.cells[key]?.backgroundColor) {
    td.style.backgroundColor = metadata.cells[key].backgroundColor;
  }

  // 检查后续单元格是否为空
  if (value) {
    const totalCols = instance.countCols();
    let hasNonEmptyCell = false;
    let availableSpace = 0;
    let nextCol = col + 1;

    // 检查从下一列到最后一列是否有非空单元格，同时计算可用空间
    while (nextCol < totalCols) {
      const nextValue = instance.getDataAtCell(row, nextCol);
      if (nextValue !== null && nextValue !== '') {
        hasNonEmptyCell = true;
        break;
      }
      availableSpace += instance.getColWidth(nextCol);
      nextCol++;
    }

    // 如果后续没有非空单元格，且不是最后一列，允许内容溢出
    if (!hasNonEmptyCell && col < totalCols - 1) {
      // 获取当前单元格的实际内容宽度
      const tempSpan = document.createElement('span');
      tempSpan.style.visibility = 'hidden';
      tempSpan.style.whiteSpace = 'nowrap';
      tempSpan.textContent = value;
      document.body.appendChild(tempSpan);
      const contentWidth = tempSpan.offsetWidth;
      document.body.removeChild(tempSpan);

      // 获取当前单元格的宽度
      const currentCellWidth = instance.getColWidth(col);

      // 只有当内容宽度小于等于（当前单元格宽度 + 可用空间）时才允许溢出
      if (contentWidth <= currentCellWidth + availableSpace) {
        td.style.overflow = 'visible';
        td.style.whiteSpace = 'nowrap';
      } else {
        td.style.overflow = 'hidden';
        td.style.textOverflow = 'ellipsis';
        td.style.whiteSpace = 'nowrap';
      }
    } else {
      td.style.overflow = 'hidden';
      td.style.textOverflow = 'ellipsis';
      td.style.whiteSpace = 'nowrap';
    }
  }

  return td;
}

// 设置表格组件的 ref
const setTableRef = (el: any, tabId: string) => {
  if (el) {
    tableRefs.value[tabId] = el
    tableComponentsMap.value.set(tabId, el)
  }
}

// 获取当前页签的表格实例
const getCurrentTableInstance = (): Handsontable | null => {
  const currentTab = tabConfigs.value.find(t => t.name === activeTab.value)
  if (!currentTab) return null

  // 优先从 tableRefs 获取
  const component = tableRefs.value[currentTab.id] || tableComponentsMap.value.get(currentTab.id)
  return component?.hotInstance || null
}

// 设置单元格颜色的函数
const setCellColor = (selection: any) => {
  if (!selection) return;

  const hot = getCurrentTableInstance();
  if (!hot) return;

  const selectedRanges = hot.getSelectedRange();
  if (!selectedRanges) return;

  const metadata = getCurrentMetadata();

  selectedRanges.forEach(range => {
    const { from, to } = range;
    for (let row = Math.min(from.row, to.row); row <= Math.max(from.row, to.row); row++) {
      for (let col = Math.min(from.col, to.col); col <= Math.max(from.col, to.col); col++) {
        const key = `${row}-${col}`;
        if (selection.color) {
          if (!metadata.cells[key]) {
            metadata.cells[key] = {};
          }
          metadata.cells[key].backgroundColor = selection.color;
        } else {
          delete metadata.cells[key]?.backgroundColor;
          if (Object.keys(metadata.cells[key] || {}).length === 0) {
            delete metadata.cells[key];
          }
        }
      }
    }
  });

  // 刷新表格
  hot.render();
}

// 处理列宽变化
const handleColumnResize = (newSize: number, column: number, isDoubleClick: boolean) => {
  const metadata = getCurrentMetadata();
  const hot = getCurrentTableInstance();

  if (!hot) return;

  // 获取所有列的宽度
  const colCount = hot.countCols();
  for (let col = 0; col < colCount; col++) {
    const width = hot.getColWidth(col);
    metadata.columnWidths[col] = width;
  }
}

// 应用列宽度
const applyColumnWidths = (hot: Handsontable, columnWidths: { [key: number]: number }) => {
  const colWidths: (number | undefined)[] = [];
  const colCount = hot.countCols();

  // 构建列宽数组
  for (let i = 0; i < colCount; i++) {
    colWidths[i] = columnWidths[i] || undefined;
  }

  // 一次性设置所有列宽
  hot.updateSettings({
    colWidths
  });
}

// 在 script setup 部分添加以下代码（添加在其他 ref 变量定义的地方）
const selectedCellContent = ref<string>('');

// 基础表格配置
const baseTableSettings: Handsontable.GridSettings = {
  data: [['', '', '', '']] as TableData,  // 提供一个初始空行
  minSpareRows: 1,
  width: '100%',
  height: () => tableHeight.value,
  stretchH: 'none',  // 改为 'none'，允许水平滚动
  fixedColumnsStart: 0,
  contextMenu: {
    items: {
      'row_above': {},
      'row_below': {},
      'col_left': {},
      'col_right': {},
      'remove_row': {},
      'remove_col': {},
      'undo': {},
      'redo': {},
      'alignment': {},
      'clear_column': {},
      'separator1': { name: '---------' },
      'set_cell_color': {
        name: '设置单元格颜色',
        submenu: {
          items: [
            {
              key: 'set_cell_color:red',
              name: '红色',
              callback() {
                setCellColor({ color: '#ffcccc' });
                return true;
              }
            },
            {
              key: 'set_cell_color:green',
              name: '绿色',
              callback() {
                setCellColor({ color: '#ccffcc' });
                return true;
              }
            },
            {
              key: 'set_cell_color:blue',
              name: '蓝色',
              callback() {
                setCellColor({ color: '#cce5ff' });
                return true;
              }
            },
            {
              key: 'set_cell_color:yellow',
              name: '黄色',
              callback() {
                setCellColor({ color: '#ffffcc' });
                return true;
              }
            },
            {
              key: 'set_cell_color:gray',
              name: '灰色',
              callback() {
                setCellColor({ color: '#e6e6e6' });
                return true;
              }
            },
            {
              key: 'set_cell_color:clear',
              name: '清除颜色',
              callback() {
                setCellColor({ color: '' });
                return true;
              }
            }
          ]
        }
      }
    }
  },
  filters: false,  // 禁用筛选
  dropdownMenu: false,  // 禁用下拉菜单
  language: 'zh-CN',
  rowHeaders: true,
  colHeaders: true,
  manualColumnResize: true,
  manualRowResize: true,
  columnSorting: false,  // 禁用列排序
  wordWrap: false,
  autoColumnSize: false,
  cells: function(row: number, col: number) {
    return {
      renderer: customRenderer
    };
  },
  afterColumnResize: handleColumnResize,
  afterLoadData: (initialLoad) => {
    const hot = getCurrentTableInstance();
    const metadata = getCurrentMetadata();

    if (hot && metadata.columnWidths) {
      applyColumnWidths(hot, metadata.columnWidths);
    }
  },
  afterSelectionEnd: (row: number, column: number) => {
    const hot = getCurrentTableInstance();
    if (hot) {
      const value = hot.getDataAtCell(row, column);
      selectedCellContent.value = value !== null ? String(value) : '';
    }
  },
  licenseKey: 'non-commercial-and-evaluation'
}

// 获取指定页签的表格设置
const getTableSettings = (tab: TabConfig): Handsontable.GridSettings => {
  const data = tableDataMap.value.get(tab.id) || [['', '', '', '']]
  return {
    ...baseTableSettings,
    data: data as TableData,
  }
}

// ========================= 页签管理函数 =========================

/**
 * 显示新增页签对话框
 */
const showAddTabDialog = () => {
  addTabForm.value.label = ''
  addTabDialogVisible.value = true
}

/**
 * 提交新增页签
 */
const submitAddTab = async () => {
  if (!addTabFormRef.value) return

  await addTabFormRef.value.validate(async (valid) => {
    if (valid) {
      isSubmitting.value = true
      try {
        const updatedTabs = await addNewTab(addTabForm.value.label)
        tabConfigs.value = updatedTabs

        // 初始化新页签的数据和元数据
        const newTab = updatedTabs[updatedTabs.length - 1]
        tableDataMap.value.set(newTab.id, [['', '', '', '']])
        metadataMap.value.set(newTab.id, { cells: {}, columnWidths: {} })

        ElMessage.success('页签添加成功')
        addTabDialogVisible.value = false

        // 切换到新页签
        activeTab.value = newTab.name
      } catch (error) {
        console.error('添加页签失败:', error)
        ElMessage.error('添加页签失败：' + (error instanceof Error ? error.message : '未知错误'))
      } finally {
        isSubmitting.value = false
      }
    }
  })
}

/**
 * 删除页签
 */
const handleTabRemove = async (tabName: string) => {
  const tab = tabConfigs.value.find(t => t.name === tabName)
  if (!tab) return

  try {
    await ElMessageBox.confirm(
      `确定要删除页签"${tab.label}"吗？删除后数据将无法恢复！`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const updatedTabs = await removeTab(tab.id)
    tabConfigs.value = updatedTabs

    // 清理相关数据
    tableDataMap.value.delete(tab.id)
    metadataMap.value.delete(tab.id)
    tableComponentsMap.value.delete(tab.id)

    // 如果删除的是当前激活的页签，切换到第一个页签
    if (activeTab.value === tabName && updatedTabs.length > 0) {
      activeTab.value = updatedTabs[0].name
    }

    ElMessage.success('页签删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除页签失败:', error)
      ElMessage.error('删除页签失败：' + (error instanceof Error ? error.message : '未知错误'))
    }
  }
}

/**
 * 开始编辑页签标签
 */
const startEditTabLabel = (tab: TabConfig) => {
  if (!tab.isRemovable) return // 默认页签不允许编辑

  editingTabId.value = tab.id
  editingTabLabel.value = tab.label

  nextTick(() => {
    tabLabelInput.value?.focus()
  })
}

/**
 * 完成编辑页签标签
 */
const finishEditTabLabel = async () => {
  if (!editingTabId.value || !editingTabLabel.value.trim()) {
    cancelEditTabLabel()
    return
  }

  try {
    const updatedTabs = await updateTabLabel(editingTabId.value, editingTabLabel.value.trim())
    tabConfigs.value = updatedTabs
    ElMessage.success('页签名称修改成功')
  } catch (error) {
    console.error('修改页签名称失败:', error)
    ElMessage.error('修改页签名称失败：' + (error instanceof Error ? error.message : '未知错误'))
  } finally {
    editingTabId.value = null
    editingTabLabel.value = ''
  }
}

/**
 * 取消编辑页签标签
 */
const cancelEditTabLabel = () => {
  editingTabId.value = null
  editingTabLabel.value = ''
}

// 添加刷新状态
const isRefreshing = ref(false)

// 处理页签切换
const handleTabClick = async (tab: TabsPaneContext) => {
  console.log('切换到页签:', tab.props.name)
  // 等待 DOM 更新
  await nextTick()
  // 重新计算高度
  calculateTableHeight()

  // 查找对应的页签配置
  const tabConfig = tabConfigs.value.find(t => t.name === tab.props.name)
  if (tabConfig) {
    await loadTableData(tabConfig.configType, tabConfig.id)

    // 等待表格实例初始化
    await nextTick()
    setTimeout(() => {
      const instance = getCurrentTableInstance()
      if (instance && tabConfig.id) {
        // 确保表格实例已正确初始化
        const data = tableDataMap.value.get(tabConfig.id)
        if (data) {
          instance.loadData(data)
        }
      }
    }, 50)
  }
}

// 修改数据加载逻辑
const loadTableData = async (type: ConfigType, tabId?: string) => {
  try {
    const config = await esGetLatestConfig(type, isRefreshing.value)
    if (config && Array.isArray(config.data) && tabId) {
      // 更新表格数据
      tableDataMap.value.set(tabId, config.data)

      // 更新元数据
      metadataMap.value.set(tabId, {
        cells: config.metadata?.cells || {},
        columnWidths: config.metadata?.columnWidths || {}
      })

      // 如果实例已经存在，立即加载数据
      const tableComponent = tableComponentsMap.value.get(tabId)
      if (tableComponent?.hotInstance) {
        tableComponent.hotInstance.loadData(config.data)
        const metadata = metadataMap.value.get(tabId)
        if (metadata?.columnWidths) {
          applyColumnWidths(tableComponent.hotInstance, metadata.columnWidths)
        }
      }
    }
  } catch (error) {
    console.error('加载数据失败:', error);
    ElMessage.error('加载数据失败，请稍后重试');
  }
};

// 修改刷新数据函数
const refreshData = async () => {
  if (isRefreshing.value) return

  isRefreshing.value = true
  try {
    const currentTab = tabConfigs.value.find(t => t.name === activeTab.value)
    if (currentTab) {
      await loadTableData(currentTab.configType, currentTab.id)
      ElMessage.success('数据已刷新')
    }
  } catch (error) {
    console.error('刷新数据失败:', error)
    ElMessage.error('刷新失败：' + (error instanceof Error ? error.message : '未知错误'))
  } finally {
    isRefreshing.value = false
  }
}

// 修改保存数据函数
const saveData = async () => {
  try {
    const currentTab = tabConfigs.value.find(t => t.name === activeTab.value)
    if (!currentTab) {
      ElMessage.error('当前页签不存在')
      return
    }

    // 尝试多种方式获取表格实例
    let tableComponent = tableRefs.value[currentTab.id] || tableComponentsMap.value.get(currentTab.id)

    // 如果还是没有，等待一下再试
    if (!tableComponent?.hotInstance) {
      await nextTick()
      tableComponent = tableRefs.value[currentTab.id] || tableComponentsMap.value.get(currentTab.id)
    }

    if (!tableComponent?.hotInstance) {
      ElMessage.error('表格实例未初始化，请稍后再试')
      console.error('Table instance not found for tab:', currentTab.id, 'Refs:', tableRefs.value, 'Map:', tableComponentsMap.value)
      return
    }

    const metadata = metadataMap.value.get(currentTab.id)

    // 获取表格数据
    const data = tableComponent.hotInstance.getData() as TableData
    const configData: ConfigData = {
      data,
      metadata: metadata || { cells: {}, columnWidths: {} }
    }

    try {
      await ElMessageBox.confirm(
        '确定要保存当前配置吗？这将覆盖已有的配置数据。',
        '保存确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )

      await esSaveConfig(currentTab.configType, configData)

      // 更新本地数据
      tableDataMap.value.set(currentTab.id, data)

      ElMessage.success('数据已成功保存')
    } catch (e) {
      if (e !== 'cancel') {
        throw e
      }
      console.log('用户取消保存操作')
    }
  } catch (error) {
    console.error('保存数据失败:', error)
    ElMessage.error('保存失败：' + (error instanceof Error ? error.message : '未知错误'))
  }
}

onBeforeMount(() => {
  console.log("beforeMounted", Date.now())
})

// 修改 onMounted
onMounted(async () => {
  console.log("onMounted", Date.now())

  // 初始化ES索引
  try {
    await initializeESIndices()
  } catch (error) {
    console.error('Failed to initialize indices:', error)
    ElMessage.error('初始化索引失败，请检查ES服务是否正常')
    return
  }

  // 设置事件监听和计算表格高度
  window.addEventListener('resize', calculateTableHeight)

  // 创建 ResizeObserver 监听容器大小变化
  const resizeObserver = new ResizeObserver(() => {
    calculateTableHeight()
  })

  // 添加 Shift+滚轮 水平滚动支持
  const addHorizontalScroll = (container: Element) => {
    container.addEventListener('wheel', (e: Event) => {
      const wheelEvent = e as WheelEvent;
      if (wheelEvent.shiftKey) {
        wheelEvent.preventDefault();
        const scrollContainer = container.querySelector('.wtHolder');
        if (scrollContainer) {
          scrollContainer.scrollLeft += wheelEvent.deltaY;
        }
      }
    }, { passive: false });
  };

  // 监听表格容器的大小变化
  const containers = document.querySelectorAll('.table-container')
  containers.forEach(container => {
    resizeObserver.observe(container);
    addHorizontalScroll(container);
  });

  // 初始计算高度
  calculateTableHeight()

  // 加载页签配置
  try {
    const loadedTabs = await esGetTabConfig()

    // 确保至少有一个页签
    if (!loadedTabs || loadedTabs.length === 0) {
      console.warn('No tabs loaded, using default tabs')
      tabConfigs.value = getDefaultTabConfig()
      // 尝试保存默认配置
      try {
        await esSaveTabConfig(tabConfigs.value)
      } catch (saveError) {
        console.warn('Failed to save default tabs:', saveError)
      }
    } else {
      tabConfigs.value = loadedTabs
    }

    // 等待 DOM 更新，确保表格组件已渲染
    await nextTick()

    // 初始化每个页签的数据和元数据
    for (const tab of tabConfigs.value) {
      if (!tableDataMap.value.has(tab.id)) {
        tableDataMap.value.set(tab.id, [['', '', '', '']])
      }
      if (!metadataMap.value.has(tab.id)) {
        metadataMap.value.set(tab.id, { cells: {}, columnWidths: {} })
      }

      // 加载页签数据
      await loadTableData(tab.configType, tab.id)
    }

    // 再次等待 DOM 更新，确保表格实例已初始化
    await nextTick()

    // 等待一小段时间确保表格实例完全初始化
    setTimeout(() => {
      // 设置默认激活页签
      if (tabConfigs.value.length > 0) {
        activeTab.value = tabConfigs.value[0].name
      }
    }, 100)
  } catch (error) {
    console.error('加载页签配置失败:', error)
    // 即使出错也显示默认页签
    tabConfigs.value = getDefaultTabConfig()
    ElMessage.warning('加载页签配置失败，使用默认配置')
  }

  // 添加样式
  const style = document.createElement('style')
  style.textContent = `
    .color-menu {
      padding: 4px 0;
    }
    .color-menu-item {
      padding: 4px 12px;
      cursor: pointer;
    }
    .color-menu-item:hover {
      background-color: #f5f5f5;
    }
  `
  document.head.appendChild(style)

  // 组件卸载时清理
  onUnmounted(() => {
    window.removeEventListener('resize', calculateTableHeight)
    resizeObserver.disconnect()
  })
})
</script>

<style scoped>
.table-editor-container {
  padding: 5px;
}

.table-card {
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-buttons {
  display: flex;
  gap: 10px;
}

.search-row {
  margin-bottom: 20px;
}

.table-container {
  margin-top: 20px;
  position: relative;
  min-height: 500px;
  overflow: hidden;
}

:deep(.handsontable) {
  font-size: 14px;
}

/* 主内容区域保持滚动条 */
:deep(.ht_master.handsontable .wtHolder) {
  overflow: auto !important;
}

/* 隐藏顶部列标题的滚动条 */
:deep(.ht_clone_top.handsontable .wtHolder) {
  overflow: hidden !important;
  overflow-x: hidden !important;
  overflow-y: hidden !important;
}

/* 隐藏左侧行号的滚动条 */
:deep(.ht_clone_left.handsontable .wtHolder) {
  overflow: hidden !important;
  overflow-x: hidden !important;
  overflow-y: hidden !important;
}

/* 隐藏左上角的滚动条 */
:deep(.ht_clone_top_left_corner.handsontable .wtHolder) {
  overflow: hidden !important;
  overflow-x: hidden !important;
  overflow-y: hidden !important;
}

:deep(.handsontable td) {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  padding: 4px 6px !important;
  position: relative;
}

:deep(.handsontable td[class*="current"]) {
  z-index: 2;
}

:deep(.handsontable td:not(:empty)) {
  z-index: 1;
}

:deep(.handsontable td:empty) {
  z-index: 0;
}

/* 移除其他可能影响的通用样式 */
:deep(.handsontable .wtHolder) {
  overflow: visible !important;
}

:deep(.handsontable .ht_clone_top) {
  z-index: 101;
}

:deep(.handsontable .ht_clone_left) {
  z-index: 102;
}

:deep(.handsontable .ht_clone_top_left_corner) {
  z-index: 103;
}

:deep(.handsontable ::-webkit-scrollbar) {
  width: 8px;
  height: 8px;
}

:deep(.handsontable ::-webkit-scrollbar-track) {
  background: #f1f1f1;
  border-radius: 4px;
}

:deep(.handsontable ::-webkit-scrollbar-thumb) {
  background: #888;
  border-radius: 4px;
}

:deep(.handsontable ::-webkit-scrollbar-thumb:hover) {
  background: #555;
}

:deep(.search-result) {
  background: rgba(255, 255, 0, 0.2) !important;
}

:deep(.handsontable td.search-result) {
  background: rgba(255, 255, 0, 0.2) !important;
}

.selected-cell-display {
  margin: 10px 0;
  padding: 8px;
  background-color: #f5f7fa;
  border-radius: 4px;
  min-height: 24px;
}

.display-label {
  font-weight: bold;
  margin-right: 8px;
  color: #606266;
}

.display-content {
  color: #303133;
  word-break: break-all;
}

/* 页签相关样式 */
.tab-label {
  display: inline-block;
  cursor: pointer;
  padding: 2px 4px;
  border-radius: 3px;
  transition: background-color 0.2s;
}

.tab-label:hover {
  background-color: rgba(64, 158, 255, 0.1);
}

:deep(.el-tabs__item) {
  position: relative;
}

:deep(.el-tabs--card > .el-tabs__header .el-tabs__item) {
  border: 1px solid #e4e7ed;
  border-bottom: none;
  border-radius: 4px 4px 0 0;
}

:deep(.el-tabs--card > .el-tabs__header .el-tabs__item.is-active) {
  border-color: #409eff;
  background-color: #409eff;
  color: white;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
